<template>
  <div v-loading="state.loading" class="container" ref="nodeRef">
    <template v-if="props.isEdit">
      <UploadFileMerak ref="uploadRef" v-model="state.fileList" :path="Path.certify" />
    </template>
    <template v-else>
      <div class="handle">
        <el-input
          v-model="searchValue"
          size="small"
          :placeholder="$t('goods_document.annex_name')"
          :suffix-icon="Search"
          clearable
          @change="init"
        />
        <el-button link @click="init">{{ $t("merak.refresh") }}</el-button>
      </div>
      <el-table class="merak-table-container" table-layout="auto" :data="state.data" :max-height="300" scrollbar-always-on>
        <el-table-column prop="name" :label="$t('goods_document.annex_name')" />
        <el-table-column :label="$t('goods_document.annex_type')">
          <template #default="{ row }">{{ (row.type ?? "").toUpperCase() }}</template>
        </el-table-column>
        <el-table-column prop="created_username" :label="$t('goods_document.create_poper')" />
        <el-table-column prop="created_at" :label="$t('goods_document.create_time')" />
        <el-table-column :label="$t('merak.action')">
          <template #default="{ row }">
            <!-- <a :href="row.file_url" target="__blank" download> -->
            <el-button type="primary" :loading="loadingKey.includes(row.gc_file_id)" link @click="download(row)">
              {{ $t("merak.download") }}
            </el-button>
            <!-- </a> -->
          </template>
        </el-table-column>
        <template #empty>
          <div v-if="state.loadedData" style="padding: 100px 40px 0">
            <img :src="EmptyPng" style="object-fit: cover; height: 130px" />
          </div>
          <div v-else></div>
        </template>
      </el-table>
    </template>
  </div>
</template>

<script setup lang="ts">
import { getCurrentInstance, ref, reactive, onMounted } from "vue";

import { useRoute } from "vue-router";

import { ElMessage, ElInput, ElButton, ElTable, ElTableColumn } from "element-plus";
import { Search } from "@element-plus/icons-vue";

import UploadFileMerak from "@/components/uploadFileMerak/index.vue";

import { ResultEnum } from "@/enums/httpEnum";
import { getTableData, saveFile } from "@/api/modules/goodsArchive/document";

import { Path, downloadFile } from "@/api/modules/upload";

import { confirmWarningMsg } from "@/utils/messageUtils";

import EmptyPng from "@/assets/images/empty.png";
import { onUnmounted } from "vue";

const props = defineProps<{
  isEdit: boolean;
  queueId?: string;
}>();

const emit = defineEmits<{
  change: [];
}>();

const currentInstance = getCurrentInstance();

const route = useRoute();

const nodeRef = ref<HTMLDivElement>();

const observeRef = ref<ResizeObserver>();

const uploadRef = ref<InstanceType<typeof UploadFileMerak>>();

const searchValue = ref<string>();

const loadingKey = ref<Array<string | number>>([]);

const recordNum = ref(0);

const state = reactive<{
  loading: boolean;
  loadedData: boolean;
  data: Array<Record<string, any>>;
  fileList: Array<Record<string, any>>;
}>({
  loading: false,
  loadedData: false,
  data: [],
  fileList: []
});

const init = async () => {
  if (!route.query.id) return;
  state.loading = !!props.queueId ? false : true;
  await getTableData(route.query.id?.toString(), "file", props.queueId).then(({ code, data }) => {
    if (code == ResultEnum.SUCCESS) {
      const filterValue = (searchValue.value ?? "").toLowerCase();
      recordNum.value = data.length;
      state.loadedData = true;
      state.data = data.filter(item => (item.name ?? "").toLowerCase().includes(filterValue));
    }
  });
  state.loading = false;
};

const download = async (row: Record<string, any>) => {
  loadingKey.value.push(row.gc_file_id);
  const link = document.createElement("a");
  link.href = row.file_url;
  link.download = row.name ?? Date.now().toString();
  link.target = "_blank";
  link.click();
  // await downloadFile(row.file_url, row.name).then(status => {
  //   if (!status) {
  //     ElMessage.error(`${row.name} ${currentInstance?.proxy?.$t("merak.download_error")}`);
  //   }
  // });
  const index = loadingKey.value.findIndex(key => key === row.gc_file_id);
  loadingKey.value.splice(index, 1);
};

onMounted(() => {
  init();
  observeRef.value = new ResizeObserver(() => {
    emit("change");
  });
  if (nodeRef.value) {
    observeRef.value.observe(nodeRef.value);
  }
});

onUnmounted(() => {
  if (!!observeRef.value && !!nodeRef.value) {
    observeRef.value.unobserve(nodeRef.value);
  }
});

defineExpose({
  reload: () => init(),
  onEdit: () => {
    state.fileList = [...state.data];
    return Promise.resolve();
  },
  onCancel: async () => {
    await init();
    return Promise.resolve();
  },
  onSave: () => {
    return new Promise(resolve => {
      confirmWarningMsg({
        msg: currentInstance?.proxy?.$t("goods_document.annex_message") ?? "",
        callback: (status: string) => {
          if (status === "confirm") {
            const file_list = uploadRef.value
              ?.getFileData()
              .map((item: Record<string, any>, index) => ({ ...item, sort: index }));
            saveFile({ goods_certify_id: route.query.id, file_list }).then(({ code, message }) => {
              if (code == ResultEnum.SUCCESS) {
                init();
                ElMessage.success(currentInstance?.proxy?.$t("goods_document.annex_success"));
                resolve(true);
              } else {
                const msg = typeof message === "string" ? message : Object.values(message)?.[0];
                ElMessage.error(msg);
              }
            });
          }
        }
      });
    });
  },
  recordNum
});
</script>

<style scoped lang="scss">
.handle {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: var(--merak-space);
  .el-input {
    width: 200px;
  }
  .el-button {
    margin: 0;
    padding: 0;
    min-width: auto;
    border: none;
    &:hover,
    &:focus {
      color: var(--el-color-primary) !important;
    }
  }
}
</style>
